package com.financial.service.integralpay.utils.balanceutils;

import com.alibaba.druid.support.json.JSONUtils;
import org.apache.http.*;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;

/**
 * @anthor wenguoqiang
 * @date: 2019/01/16 15:44
 * @company
 * @des
 **/
@Component
public class HttpClientUtils {

        @Autowired
        private CloseableHttpClient httpClient;

        @Autowired
        private RequestConfig config;

        /**
         * 不带参数的get请求，如果状态码为200，则返回body，如果不为200，则返回null
         *
         * @param url
         * @return
         * @throws Exception
         */
        public String doGet(String url) throws Exception {
            // 声明 http get 请求
            HttpGet httpGet = new HttpGet(url);

            // 装载配置信息
            httpGet.setConfig(config);

            // 发起请求
            CloseableHttpResponse response = this.httpClient.execute(httpGet);

            // 判断状态码是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                // 返回响应体的内容
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            }
            return null;
        }

    // 封装Httpclient请求
    public  String doPostJson(String url, String json,Map<String,String> headers) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        // 创建Http Post请求
        HttpPost httpPost = new HttpPost(url);
        try {
            if(headers!=null){
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    httpPost.setHeader(entry.getKey(),entry.getValue());
                }
            }

            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return resultString;
    }


        /**
         * 带参数的get请求，如果状态码为200，则返回body，如果不为200，则返回null
         *
         * @param url
         * @return
         * @throws Exception
         */
        public String doGet(String url, Map<String, Object> map) throws Exception {
            URIBuilder uriBuilder = new URIBuilder(url);

            if (map != null) {
                // 遍历map,拼接请求参数
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
                }
            }

            // 调用不带参数的get请求
            return this.doGet(uriBuilder.build().toString());

        }

        /**
         * 带参数的post请求
         *
         * @param url
         * @param map
         * @return
         * @throws Exception
         *
         */
        public String doPost(String url, Map<String, Object> map) throws Exception {
            // 声明httpPost请求
            HttpPost httpPost = new HttpPost(url);
            // 加入配置信息
            httpPost.setConfig(config);

            // 判断map是否为空，不为空则进行遍历，封装from表单对象
            if (map != null) {
                List<NameValuePair> list = new ArrayList<NameValuePair>();
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()== null?"":entry.getValue().toString()));
                }
                // 构造from表单对象
                UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, "UTF-8");
                // 把表单放到post里
                httpPost.setEntity(urlEncodedFormEntity);
            }

            // 发起请求
            CloseableHttpResponse response = this.httpClient.execute(httpPost);
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        }
    /**
     * 给HttpRequest设置请求头信息
     * @author wgq
     * @param headers
     * @param request
     * @return
     */
    @SuppressWarnings("unchecked")
    private static HttpRequest setHeaders(Map<String, Object> headers, HttpRequest request) {

        Set<Map.Entry<String, Object>> headersEntrySet = headers.entrySet();
        for (Map.Entry<String, Object> headerEntry : headersEntrySet) {

            if (!"Cookie".equals(headerEntry.getKey())) {
                request.addHeader(headerEntry.getKey(), (String) headerEntry.getValue());
            } else {
                Map<String, Object> cookies = (Map<String, Object>) headerEntry.getValue();
                Set<Map.Entry<String, Object>> cookiesEntrySet = cookies.entrySet();
                for (Map.Entry<String, Object> cookieEntrySet : cookiesEntrySet) {
                    request.addHeader(new BasicHeader("Cookie", (String) cookieEntrySet.getValue()));
                }
            }

        }

        return request;
    }
    /**
     * 带参数的post请求
     *
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public String doPostToJson(String url, Map<String, Object> map, Map<String,String> headers) throws Exception {
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);
        // 加入配置信息
        httpPost.setConfig(config);

        if(headers!=null){
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpPost.setHeader(entry.getKey(),entry.getValue());
            }
        }

        // 判断map是否为空，不为空则进行遍历，封装from表单对象


        if (map != null) {
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()== null?"":entry.getValue().toString()));
            }
            // 构造from表单对象
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, "UTF-8");
            // 把表单放到post里
            httpPost.setEntity(urlEncodedFormEntity);
        }

        // 发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpPost);
        return EntityUtils.toString(response.getEntity(), "UTF-8");
    }
    public String doPostHerde(String url, Map<String, Object> map) throws Exception {
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);
        // 加入配置信息
        //HttpRequest httpRequest = new HttpPost(url);

        if (map != null && !map.isEmpty()) {
            Map<String, Object> objMap = new HashMap<>();
            objMap.put("content-type ", "application/json; encoding=utf-8");
            setHeaders(objMap, httpPost);
        }
        httpPost.setConfig(config);

        // 判断map是否为空，不为空则进行遍历，封装from表单对象
        if (map != null) {
       /*     List<NameValuePair> list = new ArrayList<NameValuePair>();
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()== null?"":entry.getValue().toString()));
            }
            // 构造from表单对象
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, "UTF-8");
            // 把表单放到post里
            httpPost.setEntity(urlEncodedFormEntity);*/

            StringEntity s = new StringEntity( JSONUtils.toJSONString(map));
            System.out.println("json>>>>>>>>>>>>"+JSONUtils.toJSONString(map));
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");//发送json数据需要设置contentType

            // 把表单放到post里
            httpPost.setEntity(s);
        }

        // 发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpPost);
        return EntityUtils.toString(response.getEntity(), "UTF-8");
    }

    /**
     * post请求（用于请求json格式的参数）
     * @param url
     * @param params
     * @return
     */
    public static String doPostStr(String url, Map<String,Object> map,String str) throws Exception {
        String s ="";
        if (map != null && !map.isEmpty()) {
            s = JsonUtils.parseJSON(map);
        }
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);// 创建httpPost
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setHeader("Authorization", str);
        String charSet = "UTF-8";
        StringEntity entity = new StringEntity(s, charSet);
        httpPost.setEntity(entity);
        CloseableHttpResponse response = null;

        try {

            response = httpclient.execute(httpPost);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                String jsonString = EntityUtils.toString(responseEntity);
                return jsonString;
            }
            else{
                System.err.println("请求返回:"+state+"("+url+")");
            }
        }
        finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

